<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Order Management</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link th:href="@{/css/custom.css}" rel="stylesheet">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">My App</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" href="/page/home">Home</a>
            </li>
            <li class="nav-item active">
                <a class="nav-link" href="/page/orders">Orders <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/page/products">Product </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="/page/members">Member </a>
            </li>
        </ul>
    </div>
</nav>

<!-- Sidebar -->
<div class="container-fluid">
    <div class="row">
        <nav class="col-md-2 d-none d-md-block bg-light sidebar custom-sidebar">
            <div class="sidebar-sticky">
                <ul class="nav flex-column custom-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="/page/home">
                            <span data-feather="home"></span>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link" href="/page/orders">
                            <span data-feather="file"></span>
                            Orders
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/page/products">
                            <span data-feather="shopping-cart"></span>
                            Product
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/page/members">
                            <span data-feather="users"></span>
                            Member
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Orders</h1>
            </div>
            <button type="button" class="btn btn-primary mb-3" id="createOrderButton">Create Order</button>
            <button type="button" class="btn btn-danger mb-3" id="deleteSelectedButton">Delete Selected</button>
            <table class="table table-striped" id="ordersTable">
                <thead>
                <tr>
                    <th>Select</th>
                    <th>ID</th>
                    <th>Customer Name</th>
                    <th>Total Amount</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                <!-- Orders will be loaded here via AJAX -->
                </tbody>
            </table>
        </main>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="createOrderModal" tabindex="-1" role="dialog" aria-labelledby="createOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createOrderModalLabel">Create Order</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="createOrderForm">
                    <div class="form-group">
                        <label for="customerName">Customer Name</label>
                        <input type="text" class="form-control" id="customerName" required>
                    </div>
                    <div class="form-group">
                        <label for="totalAmount">Total Amount</label>
                        <input type="number" class="form-control" id="totalAmount" required>
                    </div>
                    <div class="form-group">
                        <label for="status">Status</label>
                        <input type="text" class="form-control" id="status" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="submitOrderButton">Create</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js"></script>
<script>
    $(document).ready(function() {
        function loadOrders() {
            $.ajax({
                url: '/order/getOrderList',
                method: 'GET',
                success: function(response) {
                    var data = response.data; // Extract data from response
                    var tbody = $('#ordersTable tbody');
                    tbody.empty(); // Clear existing rows
                    data.forEach(function(order) {
                        var row = `
                        <tr>
                            <td><input type="checkbox" class="delete-order" data-id="${order.id}"></td>
                            <td>${order.id}</td>
                            <td>${order.name}</td>
                            <td>${order.price}</td>
                            <td>${order.address}</td>
                            <td>
                                <button class="btn btn-sm btn-primary edit-order" data-id="${order.id}">Edit</button>
                                <button class="btn btn-sm btn-danger delete-order" data-id="${order.id}">Delete</button>
                            </td>
                        </tr>
                    `;
                        tbody.append(row);
                    });
                },
                error: function(error) {
                    console.error('Error loading orders:', error);
                }
            });
        }

        // Load orders on page load
        loadOrders();

        // Show modal when create order button is clicked
        $('#createOrderButton').click(function() {
            $('#createOrderModal').modal('show');
        });

        $(document).on('click', '.edit-order', function() {
            var orderId = $(this).data('id');
            // Open a modal for editing the order
            $('#createOrderModal').modal('show');
            // Load order details into the modal
            $.ajax({
                url: '/order/getOrderById/' + orderId,
                method: 'GET',
                success: function(data) {
                    $('#customerName').val(data.name);
                    $('#totalAmount').val(data.price);
                    $('#status').val(data.address);
                    $('#submitOrderButton').text('Update').attr('data-id', orderId);
                },
                error: function(error) {
                    console.error('Error loading order details:', error);
                }
            });
        });

        $('#submitOrderButton').click(function() {
            var orderId = $(this).data('id');
            var customerName = $('#customerName').val();
            var totalAmount = $('#totalAmount').val();
            var status = $('#status').val();

            var url = orderId ? '/order/updateOrder/' + orderId : '/order/createOrder';
            var method = orderId ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                method: method,
                data: {
                    customerName: customerName,
                    totalAmount: totalAmount,
                    status: status
                },
                success: function(response) {
                    console.log('Order saved successfully:', response.data); // Extract data from response
                    $('#createOrderModal').modal('hide');
                    loadOrders(); // Reload orders to reflect the changes
                },
                error: function(error) {
                    console.error('Error saving order:', error);
                }
            });
        });

        $('#deleteSelectedButton').click(function() {
            var selectedOrderIds = [];
            $('.delete-order:checked').each(function() {
                selectedOrderIds.push($(this).data('id'));
            });

            if (selectedOrderIds.length === 0) {
                alert('Please select at least one order to delete.');
                return;
            }

            if (confirm('Are you sure you want to delete the selected orders?')) {
                $.ajax({
                    url: '/order/deleteBatch',
                    method: 'DELETE',
                    contentType: 'application/json',
                    data: JSON.stringify(selectedOrderIds),
                    success: function(response) {
                        console.log('Orders deleted successfully:', response.data);
                        loadOrders(); // Reload orders to reflect the changes
                    },
                    error: function(error) {
                        console.error('Error deleting orders:', error);
                        alert('Error deleting orders: ' + error.responseText);
                    }
                });
            }
        });

    });
</script>

</body>
</html>